<template>
	<div class="system-user-container">
		<el-card class="box-card">
			<div>
				<div class="my_btn_lay">
					<div class="my_flex my_btn" @click="searchEvent">
						<div class="my_flex_layout">
							<i class="vxe-icon--search"></i>
							<span>查找</span>
						</div>
					</div>

					<div class="my_flex my_btn ml20" @click="resetEvent">
						<div class="my_flex_layout">
							<i class="vxe-icon--refresh"></i>
							<span>重置</span>
						</div>
					</div>

					<div class="my_flex my_btn ml20" @click="addDefaultBlank">
						<div class="my_flex_layout">
							<i class="vxe-icon--plus"></i>
							<span>新增</span>
						</div>
					</div>

					<div class="my_flex my_btn ml20" @click="deleteTable">
						<div class="my_flex_layout">
							<i class="fa fa-trash-o"></i>
							<span>删除</span>
						</div>
					</div>

					<div class="my_flex my_btn ml20" @click="funnelEvent">
						<div class="my_flex_layout">
							<i class="vxe-icon--download"></i>
							<span>导出</span>
						</div>
					</div>

					<div class="my_flex my_btn ml20" @click="printTab">
						<div class="my_flex_layout">
							<i class="vxe-icon--print"></i>
							<span>打印</span>
						</div>
					</div>

					<div class="my_flex my_btn ml20" @click="add_shouw">
						<div class="my_flex_layout">
							<i class="el-icon-folder-opened"></i>
							<span>付出方式</span>
						</div>
					</div>

					<div class="my_flex my_btn ml20" @click="showAmendFun">
						<div class="my_flex_layout">
							<i class="el-icon-edit"></i>
							<span>编辑</span>
						</div>
					</div>
					<div class="my_flex my_btn ml20" @click="editClosedEvent">
						<div class="my_flex_layout">
							<i class="el-icon-folder-add"></i>
							<span>保存</span>
						</div>
					</div>
				</div>

				<vxe-form :data="selectFrom" title-align="left" prevent-submit title-colon>
					<vxe-form-item title="出票开始日期" field="time" span="5" :item-render="{}">
						<template #default="{ data }">
							<el-date-picker value-format="YYYY-MM-DD HH:mm:ss" v-model="data.time1" type="date" placeholder="开始时间"> </el-date-picker>
						</template>
					</vxe-form-item>

					<vxe-form-item title="到期开始日期" field="time" span="5" :item-render="{}">
						<template #default="{ data }">
							<el-date-picker value-format="YYYY-MM-DD HH:mm:ss" v-model="data.time3" type="date" placeholder="开始时间"> </el-date-picker>
						</template>
					</vxe-form-item>

					<vxe-form-item title="合同名称" field="contractId" span="5" :item-render="{}">
						<template #default="{ data }">
							<el-select style="width: 100%" clearable filterable v-model="data.contractId" placeholder="合同名称">
								<el-option v-for="item in contractData" :key="item.id" :label="item.contractName" :value="item.id"></el-option>
							</el-select>
						</template>
					</vxe-form-item>

					<vxe-form-item title="中介机构" field="intermediaryUnitId" span="5" :item-render="{}">
						<template #default="{ data }">
							<el-select style="width: 100%" clearable filterable v-model="data.intermediaryUnitId" placeholder="中介机构">
								<el-option v-for="item in selectFrom.unitsData" :key="item.id" :label="item.unitName" :value="item.id"> </el-option>
							</el-select>
						</template>
					</vxe-form-item>

					<vxe-form-item title="是否回发票" field="invoiceBack" span="4" :item-render="{}">
						<template #default="{ data }">
							<el-select style="width: 100%" clearable filterable v-model="data.invoiceBack" placeholder="是否回发票">
								<el-option v-for="item in selectFrom.isUseData" :key="item.value" :label="item.label" :value="item.value"> </el-option>
							</el-select>
						</template>
					</vxe-form-item>

					<vxe-form-item title="出票截止日期" field="time" span="5" :item-render="{}">
						<template #default="{ data }">
							<el-date-picker value-format="YYYY-MM-DD HH:mm:ss" v-model="data.time2" type="date" placeholder="开始时间"> </el-date-picker>
						</template>
					</vxe-form-item>

					<!-- 到期日期 -->
					<vxe-form-item title="到期结束日期" field="time" span="5" :item-render="{}">
						<template #default="{ data }">
							<el-date-picker value-format="YYYY-MM-DD HH:mm:ss" v-model="data.time4" type="date" placeholder="开始时间"> </el-date-picker>
						</template>
					</vxe-form-item>

					<!-- 兑付日 -->
					<!-- <vxe-form-item title="兑付开始日期" field="time" span="6" :item-render="{}">
						<template #default="{ data }">
							<el-date-picker value-format="YYYY-MM-DD HH:mm:ss" v-model="data.time5" type="date" placeholder="开始时间"> </el-date-picker>
						</template>
					</vxe-form-item> -->

					<vxe-form-item title="兑付结束日期" field="time" span="5" :item-render="{}">
						<template #default="{ data }">
							<el-date-picker value-format="YYYY-MM-DD HH:mm:ss" v-model="data.time6" type="date" placeholder="结束时间"> </el-date-picker>
						</template>
					</vxe-form-item>

					<vxe-form-item title="票面金额" field="" span="5" :item-render="{}">
						<template #default="{ data }">
							<div class="money_scope" style="width: 100%">
								<el-input v-model="data.startMoney" placeholder="启始值" style="width: 45%"> </el-input>
								<i class="el-icon-minus"></i>
								<el-input v-model="data.endMoney" placeholder="结束值" style="width: 45%"> </el-input>
							</div>
						</template>
					</vxe-form-item>

					<!-- <vxe-form-item title="汇票号码" field="num" span="6" :item-render="{}">
						<template #default="{ data }">
							<el-input style="width: 100%" v-model="data.num" placeholder="请输入汇票号码"></el-input>
						</template>
					</vxe-form-item>

					<vxe-form-item title="出票单位" field="ticketIssuingUnitId" span="6" :item-render="{}">
						<template #default="{ data }">
							<el-select style="width: 100%" clearable filterable v-model="data.ticketIssuingUnitId" placeholder="请选择出票单位">
								<el-option v-for="item in selectFrom.unitsData" :key="item.id" :label="item.unitName" :value="item.id"> </el-option>
							</el-select>
						</template>
					</vxe-form-item>
					<vxe-form-item title="承兑单位" field="acceptanceUnitId" span="6" :item-render="{}">
						<template #default="{ data }">
							<el-select style="width: 100%" clearable filterable v-model="data.acceptanceUnitId" placeholder="请选择承兑单位">
								<el-option v-for="item in selectFrom.unitsData" :key="item.id" :label="item.unitName" :value="item.id"> </el-option>
							</el-select>
						</template>
					</vxe-form-item>

					<vxe-form-item title="是否已使用" field="isUse" span="6" :item-render="{}">
						<template #default="{ data }">
							<el-select style="width: 100%" clearable filterable v-model="data.isUse" placeholder="是否已使用">
								<el-option v-for="item in selectFrom.isUseData" :key="item.value" :label="item.label" :value="item.value"> </el-option>
							</el-select>
						</template>
					</vxe-form-item>
					<vxe-form-item title="收票单位" field="receivingUnitId" span="6" :item-render="{}">
						<template #default="{ data }">
							<el-select style="width: 100%" clearable filterable v-model="data.receivingUnitId" placeholder="请选择收票单位">
								<el-option v-for="item in selectFrom.unitsData" :key="item.id" :label="item.unitName" :value="item.id"> </el-option>
							</el-select>
						</template>
					</vxe-form-item> -->

					<!-- <vxe-form-item align="right" span="24" collapse-node>
						<template #default>
							<vxe-button status="primary" content="搜索" @click="searchEvent"></vxe-button>
							<vxe-button content="重置" @click="resetEvent"></vxe-button>
						</template>
					</vxe-form-item> -->
				</vxe-form>
			</div>

			<!-- <vxe-toolbar ref="xToolbar" custom>
				<template #buttons>
					<vxe-button type="text" icon="fa fa-plus" content="新增" @click="addDefaultBlank"></vxe-button>
					<vxe-button type="text" icon="fa fa-trash-o" content="删除" @click="deleteTable"></vxe-button>

					<vxe-button type="text" icon="fa fa-plus" content="新增付出方式" @click="add_shouw"></vxe-button>
				</template>
				<template #tools>
					<vxe-button type="text" icon="vxe-icon--print" class="tool-btn" @click="printTab"></vxe-button>
					<vxe-button type="text" icon="vxe-icon--download" class="tool-btn" @click="funnelEvent"></vxe-button>
				</template>
			</vxe-toolbar> -->
			<!-- @edit-closed="editClosedEvent" -->
			<vxe-table
				align="center"
				height="730"
				border
				keep-source
				:scroll-x="{ enabled: false }"
				:scroll-y="{ enabled: false }"
				ref="xTable1"
				:export-config="{}"
				resizable
				show-overflow
				:data="tableData"
				:edit-config="{ trigger: 'manual', mode: 'row',icon: 'false' }"
				class="mytable-style"
				:row-class-name="rowClassName"
				:edit-rules="validRules"
				@checkbox-all="selectAllChangeEvent1"
				@checkbox-change="selectChangeEvent1"
				show-footer
				:footer-method="footerMethod"
			>
				<vxe-column type="checkbox" align="center" width="60" fixed="left"></vxe-column>
				<vxe-column type="seq" align="center" title="序号" width="60"></vxe-column>

				<vxe-column width="100" field="num" title="汇票号码" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
				<vxe-column width="100" field="amount" title="票面金额" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.amount) }}</template>
				</vxe-column>

				<vxe-column
					width="105"
					field="ticketIssuanceTime"
					title="出票日期"
					:edit-render="{ name: '$input', placeholder: '请选择日期', props: { type: 'date', placeholder: '请选择日期' } }"
				></vxe-column>

				<vxe-column
					width="105"
					field="dueTime"
					title="到期日期"
					:edit-render="{ name: '$input', placeholder: '请选择日期', props: { type: 'date', placeholder: '请选择日期' } }"
				></vxe-column>

				<vxe-column width="130" field="ticketIssuingUnitId" title="出票单位" :edit-render="{ type: 'default' }">
					<template v-slot:edit="scope">
						<el-select clearable filterable v-model="scope.row.ticketIssuingUnitId">
							<el-option v-for="item in selectFrom.unitsData" :key="item.id" :label="item.unitName" :value="item.id"></el-option>
						</el-select>
					</template>
					<template v-slot="{ row }">{{ getSelectLabel(row.ticketIssuingUnitId, selectFrom.unitsData) }}</template>
				</vxe-column>

				<vxe-column width="130" field="acceptanceUnitId" title="承兑单位" :edit-render="{ type: 'default' }">
					<template v-slot:edit="scope">
						<el-select clearable filterable v-model="scope.row.acceptanceUnitId">
							<el-option v-for="item in selectFrom.unitsData" :key="item.id" :label="item.unitName" :value="item.id"></el-option>
						</el-select>
					</template>
					<template v-slot="{ row }">{{ getSelectLabel(row.acceptanceUnitId, selectFrom.unitsData) }}</template>
				</vxe-column>

				<vxe-column width="130" field="contractId" title="合同名称" :edit-render="{ type: 'default' }">
					<template v-slot:edit="scope">
						<el-select clearable filterable v-model="scope.row.contractId">
							<el-option v-for="item in contractData" :key="item.id" :label="item.contractName" :value="item.id"></el-option>
						</el-select>
					</template>
					<template v-slot="{ row }">{{ getSelectLabelelListTop(row.contractId, contractData) }}</template>
				</vxe-column>

				<vxe-column
					width="105"
					field="paymentTime"
					title="付款时间"
					:edit-render="{ name: '$input', placeholder: '请选择日期', props: { type: 'date', placeholder: '请选择日期' } }"
				></vxe-column>

				<vxe-column width="100" field="receivingUnitId" title="收票单位" :edit-render="{ type: 'default' }">
					<template v-slot:edit="scope">
						<el-select clearable filterable v-model="scope.row.receivingUnitId">
							<el-option v-for="item in selectFrom.unitsData" :key="item.id" :label="item.unitName" :value="item.id"></el-option>
						</el-select>
					</template>
					<template v-slot="{ row }">{{ getSelectLabel(row.receivingUnitId, selectFrom.unitsData) }}</template>
				</vxe-column>

				<vxe-column width="100" field="wayOfPayingId" title="付出方式" :edit-render="{ type: 'default' }">
					<template v-slot:edit="scope">
						<el-select clearable filterable v-model="scope.row.wayOfPayingId">
							<el-option v-for="item in selectFrom.playData" :key="item.id" :label="item.type" :value="item.id"></el-option>
						</el-select>
					</template>
					<template v-slot="{ row }">{{ getSelectLabel_play(row.wayOfPayingId, selectFrom.playData) }}</template>
				</vxe-column>

				<vxe-column width="100" field="intermediaryUnitId" title="中介机构" :edit-render="{ type: 'default' }">
					<template v-slot:edit="scope">
						<el-select clearable filterable v-model="scope.row.intermediaryUnitId">
							<el-option v-for="item in selectFrom.unitsData" :key="item.id" :label="item.unitName" :value="item.id"></el-option>
						</el-select>
					</template>
					<template v-slot="{ row }">{{ getSelectLabel(row.intermediaryUnitId, selectFrom.unitsData) }}</template>
				</vxe-column>

				<vxe-column
					width="105"
					field="startTime"
					title="起始日"
					:edit-render="{ name: '$input', placeholder: '请选择日期', props: { type: 'date', placeholder: '请选择日期' } }"
				></vxe-column>
				<vxe-column
					width="105"
					field="redemptionTime"
					title="兑付日"
					:edit-render="{ name: '$input', placeholder: '请选择日期', props: { type: 'date', placeholder: '请选择日期' } }"
				></vxe-column>

				<vxe-column width="100" field="interest" title="利息金额" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.interest) }}</template>
				</vxe-column>

				<vxe-column width="100" field="discountRate" title="贴现率" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>

				<vxe-column width="100" field="invoiceBack" title="是否回发票" :edit-render="{ name: '$select', options: selectFrom.isUseData }"></vxe-column>

				<vxe-column width="100" field="remarks" title="备注" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>

				<!-- <vxe-column field="pictureUrl" title="上传图片" :edit-render="{ name: '$select', options: selectFrom.typeArry }"></vxe-column> -->

				<vxe-column title="操作" fixed="right" width="100">
					<template #default="{ row }">
						<vxe-button status="primary" @click="openFileBtn(row)">文件列表</vxe-button>
					</template>
				</vxe-column>
			</vxe-table>
			<!-- 弹窗 -->
			<vxe-modal v-model="bankFrom.isshow" title="付出方式" width="600" height="420" show-zoom resize remember>
				<template #default>
					<vxe-toolbar perfect>
						<template #buttons>
							<vxe-button icon="fa fa-plus" status="perfect" content="新增" @click="addbankShow"></vxe-button>
							<vxe-button icon="fa fa-trash-o" status="perfect" content="删除" @click="deleteTable_show"></vxe-button>
						</template>
					</vxe-toolbar>
					<vxe-table
						border
						:height="300"
						show-overflow
						ref="xTableShow"
						:data="bankFrom.shoWData"
						:edit-config="{ trigger: 'click', mode: 'row', showStatus: true }"
						@checkbox-all="selectAllChangeEvent1_show"
						@checkbox-change="selectChangeEvent1_show"
						@edit-closed="editClosedEvent_show"
					>
						<vxe-column type="checkbox" width="60" align="center"></vxe-column>
						<vxe-column type="seq" width="60" align="center"></vxe-column>
						<vxe-column field="type" title="付出方式" width="400" :edit-render="{ name: 'input' }"></vxe-column>
					</vxe-table>
				</template>
			</vxe-modal>

			<!-- 文件列表 -->
			<vxe-modal v-model="showFileList.isShow" title="文件列表" width="600" height="420" show-zoom resize remember>
				<template #default>
					<vxe-toolbar perfect>
						<template #buttons>
							<vxe-button icon="fa fa-plus" status="perfect" content="上传文件" @click="uploadingbutton()"></vxe-button>
							<!-- <vxe-button   status="primary" @click="uploadingbutton(row)">上传文件</vxe-button> -->
						</template>
					</vxe-toolbar>
					<vxe-table border :height="300" show-overflow ref="xTableShow" :data="showFileList.fileList">
						<vxe-column type="seq" width="60" align="center"></vxe-column>
						<vxe-column field="name" title="文件列表"></vxe-column>
						<vxe-column title="操作" fixed="right" align="center" width="230">
							<template #default="{ row }">
								<vxe-button status="primary" @click="download(row)">下载文件</vxe-button>
								<vxe-button @click="deleteFile(row)">删除文件</vxe-button>
							</template>
						</vxe-column>
					</vxe-table>
				</template>
			</vxe-modal>
		</el-card>
	</div>
</template>

<script lang="ts">
import { toRefs, reactive, ref, toRaw, onMounted, nextTick } from 'vue';

import { ElMessage, ElMessageBox } from 'element-plus';
import {
	axios_SelList,
	axios_ticketselList,
	axios_ticketdel,
	axios_wayselList,
	axios_ticketup,
	axios_ticketadd,
	axios_waydel,
	axios_wayadd,
	axios_wayup,
	axios_fileupload,
	// downloadURL, //下载地址
	axiosGetFileList, //获取文件列表
	axiosGetFiledel, //删除文件
	axios_selListTop,
} from '/@/api/basicsUrl/index';

import { GenNonDuplicateID } from '/@/utils/formatTime';
import { VXETable, VxeTablePropTypes } from 'vxe-table';
import { transitionNumber } from '/@/utils/transitionNumber';

export default {
	name: 'BusinessTicket',
	setup() {
		const xTable1 = ref({} as VxeTableInstance);
		const xToolbar = ref({} as VxeToolbarInstance);

		// 打印样式
		// 打印样式
		const printStyle = `
            .title {
              text-align: center;
            }
            .my-list-row {
              display: inline-block;
              width: 100%;
            }
            .my-list-col {
              float: left;
              width: 33.33%;
              height: 28px;
              line-height: 28px;
            }
            .my-top,
            .my-bottom {
              font-size: 12px;
            }
            .my-top {
              margin-bottom: 5px;
            }
            .my-bottom {
              margin-top: 30px;
              text-align: right;
            }
            `;

		// 打印顶部内容模板
		const topHtml = `
            <h1 class="title">出货单据</h1>
            <div class="my-top">
              <div class="my-list-row">
                <div class="my-list-col">商品名称： </div>
                <div class="my-list-col">发货单号：X2665847132654</div>
                <div class="my-list-col">发货日期：2020-09-20</div>
              </div>
              <div class="my-list-row">
                <div class="my-list-col">收货姓名： </div>
                <div class="my-list-col">收货地址：火星第七区18号001</div>
                <div class="my-list-col">联系电话：10086</div>
              </div>
            </div>
            `;

		// 打印底部内容模板
		const bottomHtml = `
            <div class="my-bottom">
              <div class="my-list-row">
                <div class="my-list-col"></div>
                <div class="my-list-col">创建人： </div>
                <div class="my-list-col">创建日期：2020-09-20</div>
              </div>
            </div>
            `;
		/**
		 * @Author: lilin_:）
		 * @name: 默认空白数组
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		let defaultBlankData = [
			{
				iswebAdd: true,
				webid: GenNonDuplicateID(),
				wayOfPayingId: '', //付款方式
				num: '',
				amount: '',
				ticketIssuanceTime: '',
				dueTime: '',
				ticketIssuingUnitId: '',
				ticketIssuingUnit: '',
				acceptanceUnitId: '',
				acceptanceUnit: '',
				paymentTime: '',
				receivingUnitId: '',
				receivingUnit: '',
				wayOfPaying: '',
				intermediaryUnitId: '',
				intermediaryUnit: '',
				startTime: '',
				redemptionTime: '',
				interest: '',
				discountRate: '',
				invoiceBack: '',
				pictureUrl: '',
				remarks: '',
				contractId: '', //合同名称
			},
		];

		let defaultBlankDataShow = [
			{
				iswebAdd: true,
				webid: GenNonDuplicateID(),
				bank: '', //银行名字
			},
		];
		const validRules = ref({
			ticketIssuanceTime: [{ required: true, message: '出票时间必选' }],
			amount: [{ required: true, message: '票面金额必填' }],
		} as VxeTablePropTypes.EditRules);

		const state: any = reactive({
			contractData: [], // 合同数据
			addList: [], //前端加的数据
			responseData: [], //后端返回的数据
			showCount: '', //保存合计
			yu: 0, //计算票数
			// 文件数组
			bankFrom: {
				isshow: false, //弹窗控制
				shoWData: [], //表格数据
				selectData: [], //多选的数据
			},
			// 文件列表
			showFileList: {
				isShow: false, //是否打开
				fileList: [], // 文件集合
				sasveFileItem: '', //存储数据对象
			},
			selectFrom: {
				on: 0, //默认是0，1是点击
				time1: '', //出票时间
				time2: '', //出票时间
				time3: '', //到期时间
				time4: '', //到期时间
				time5: '', // 兑付日
				time6: '', // 兑付日
				intermediaryUnitId: '', //中介机构ID
				contractId: '', //合同名称
				invoiceBack: '', //是否发票

				startMoney: '', //开始金额
				endMoney: '', //结束金额
				num: '', //汇编号码
				ticketIssuingUnitId: '', //出票单位ID
				// amount: '', //票面金额 14.55-15.55
				acceptanceUnitId: '', //承兑单位ID
				isUse: '', //是否已使用 1是0否
				isUseData: [
					{ label: '是', value: '1' },
					{ label: '否', value: '0' },
				],
				playData: [], //付款方式

				receivingUnitId: '', //收票单位ID

				// type: '', //单位类型1供应商2客户3公司员工
				typeArry: [
					{ label: '供应商', value: '1' },
					{ label: '客户', value: '2' },
					{ label: '公司员工', value: '3' },
				], //单位类型1供应商2客户3公司员工
				unitsData: [], //多数据
			},
			tableData: [], //表格数据
			selecttableData: [], //多选
		});

		const selectAllChangeEvent1: VxeTableEvents.CheckboxAll = ({ checked, records }: any) => {
			console.log(checked ? '所有勾选事件' : '所有取消事件', records);
			state.selecttableData = records;
		};

		const selectChangeEvent1: VxeTableEvents.CheckboxChange = ({ checked, records }: any) => {
			state.tableData.forEach((item2: any) => {
				item2.hghligHt = false;
			});
			state.selecttableData = records;
			console.log(checked ? '勾选事件' : '取消事件', records);
			state.selecttableData.forEach((item: any) => {
				if (item.iswebAdd) {
					// 前端的数据
					state.tableData.forEach((item2: any) => {
						if (item.webid == item2.webid) {
							item2.hghligHt = true;
						}
					});
				} else {
					state.tableData.forEach((item2: any) => {
						if (item.id == item2.id) {
							item2.hghligHt = true;
						}
					});
				}
			});
		};

		const selectAllChangeEvent1_show: VxeTableEvents.CheckboxAll = ({ checked, records }: any) => {
			console.log(checked ? '所有勾选事件' : '所有取消事件', records);
			state.bankFrom.selectData = records;
		};

		const selectChangeEvent1_show: VxeTableEvents.CheckboxChange = ({ checked, records }: any) => {
			state.bankFrom.selectData = records;
			console.log(checked ? '勾选事件' : '取消事件', records);
		};

		//打开文件列表
		const openFileBtn = async (item: any) => {
			state.showFileList.sasveFileItem = item;
			let { code, obj }: any = await axiosGetFileList({ dataSheet: 3, id: item.id });
			if (code == 200) {
				state.showFileList.isShow = true;
				state.showFileList.fileList = obj.map((item: any) => {
					return {
						name: item,
					};
				});
			}

			// 获取数据
		};

		// 刷新文件列表数据
		const shuaxingFileListFun = async () => {
			let { obj }: any = await axiosGetFileList({ dataSheet: 3, id: state.showFileList.sasveFileItem.id });
			state.showFileList.fileList = obj.map((item: any) => {
				return {
					name: item,
				};
			});
		};

		/**
		 * @Author: lilin_:）
		 * @name: 通讯录接口
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const getProjectName = async () => {
			let resData: any = await axios_SelList({ unitName: '', contactPerson: '', type: '2' });
			state.selectFrom.unitsData = resData.obj;
			console.log(toRaw(resData.obj), '11111111');
		};

		// 获取合同数据新增内容
		let getContractData = async () => {
			let { code, obj } = await axios_selListTop();
			if (code == 200) {
				state.contractData = obj;
			}
		};

		// 搜索
		const searchEvent: VxeFormEvents.Submit = async () => {
			// VXETable.modal.message({ content: '查询事件', status: 'info' });
			state.selectFrom.on = 1; //状态
			await gitTableList();
		};

		// 获取列表
		const gitTableList = () => {
			let amountData = '';
			if (state.selectFrom.startMoney) {
				if (state.selectFrom.endMoney) {
					amountData = `${state.selectFrom.startMoney}-${state.selectFrom.endMoney}`;
				}
			}
			let data = {
				// num: state.selectFrom.num, //汇编号码
				contractId: state.selectFrom.contractId, //合同名称

				amount: amountData, //金额区间
				intermediaryUnitId: state.selectFrom.intermediaryUnitId, //中介机构
				on: state.selectFrom.on, //状态
				time1: state.selectFrom.time1, // 出票时间
				time2: state.selectFrom.time2, // 出票时间

				time3: state.selectFrom.time3, // 到期时间
				time4: state.selectFrom.time4, // 到期时间
				time5: state.selectFrom.time5, // 兑付日
				time6: state.selectFrom.time6, // 兑付日

				invoiceBack: state.selectFrom.invoiceBack, //是否回票

				// ticketIssuingUnitId: state.selectFrom.ticketIssuingUnitId, //出票单位ID

				// acceptanceUnitId: state.selectFrom.acceptanceUnitId,
				// isUse: state.selectFrom.isUse,
				// receivingUnitId: state.selectFrom.receivingUnitId,
			};

			console.log(toRaw(data), '获取到的搜索数据');
			axios_ticketselList(data).then((res: any) => {
				if (res.code == 200) {
					// 重置数据
					state.addList = [];
					// 添加20条数据
					for (let index = 0; index < 20; index++) {
						state.addList.push(
							defaultBlankData.map((item: any) => {
								return {
									...item,
									...{
										webid: GenNonDuplicateID(),
									},
								};
							})[0]
						);
					}
					state.responseData = res.obj;
					state.tableData = [...state.responseData, ...state.addList];
					state.selecttableData = [];
					// state.tableData = res.obj;
					state.showCount = res.data.count;
					state.yu = res.data.yu;
				}
			});
		};

		/**
		 * @Author: lilin_:）
		 * @name: 重置搜索表单
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const resetEvent: VxeFormEvents.Reset = async () => {
			state.selectFrom.startMoney = '';
			state.selectFrom.endMoney = '';
			state.selectFrom.num = '';
			state.selectFrom.ticketIssuingUnitId = '';
			state.selectFrom.acceptanceUnitId = '';
			state.selectFrom.isUse = '';
			state.selectFrom.receivingUnitId = '';
			state.selectFrom.contractId = ''; //合同名称

			// 重置
			state.selectFrom.on = 0;
			state.selectFrom.time1 = '';
			state.selectFrom.time2 = '';
			state.selectFrom.time3 = '';
			state.selectFrom.time4 = '';
			state.selectFrom.time5 = '';
			state.selectFrom.time6 = '';
			state.selectFrom.invoiceBack = '';
			state.selectFrom.intermediaryUnitId = '';
			await gitTableList();
			// VXETable.modal.message({ content: '重置事件', status: 'info' });
		};

		// 付出方式
		const getplaData = () => {
			axios_wayselList().then((res) => {
				console.log(res, 'aaaaaa');
				state.selectFrom.playData = res.obj;
				state.bankFrom.shoWData = res.obj;
			});
		};

		onMounted(() => {
			getplaData(); //查询付款方式
			getProjectName(); //单位名称
			gitTableList();
			getContractData();

			// let a = GenNonDuplicateID()
			// console.log(a)
		});

		//实时更新
		const editClosedEvent: VxeTableEvents.EditClosed = ({ row, column }) => {
			console.log(toRaw(row), '11111');
			if (state.selecttableData.length == 1) {
				let row = state.selecttableData[0];
				if (row.iswebAdd) {
					// 走保存接口
					// console.log(toRaw(row), '我是前端提交');
					axios_ticketadd(row).then((res) => {
						// console.log(res, '是否啊添加');
						if (res.code == 200) {
							state.selectFrom.on = 2; //状态
							gitTableList();
							VXETable.modal.message({ content: '新增成功!', status: 'success' });
						}
					});
				} else {
					axios_ticketup(row).then((res) => {
						if (res.code == 200) {
							state.selectFrom.on = 1; //状态
							gitTableList();
							VXETable.modal.message({ content: '编辑成功！', status: 'success' });
						}
					});
					// console.log(toRaw(row), '我是后段提交');
				}
			} else if (state.selecttableData.length == 0) {
				VXETable.modal.message({ content: '您还没有选中行', status: 'warning' });
			} else {
				VXETable.modal.message({ content: '只能选中一行编辑', status: 'warning' });
			}
		};

		const footerMethod: VxeTablePropTypes.FooterMethod = ({ columns, data }) => {
			return [
				columns.map((column, columnIndex) => {
					// console.log(columnIndex, '1');
					if (columnIndex === 2) {
						return '合计';
					}
					if (columnIndex === 3) {
						return `${state.showCount}`;
					}
					if (columnIndex === 4) {
						return '库存商票合计';
					}
					if (columnIndex === 5) {
						return `${state.yu}`;
					}

					return '';
				}),
			];
		};

		/**
		 * @Author: lilin_:）
		 * @name: 关联表格
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		nextTick(() => {
			// 将表格和工具栏进行关联
			const $table = xTable1.value;
			const $toolbar = xToolbar.value;
			$table.connect($toolbar);
		});

		/**
		 * @Author: lilin_:）
		 * @name: 新增空白行
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const addDefaultBlank = () => {
			let addArry = defaultBlankData.map((item: any) => {
				return {
					...item,
					...{
						webid: GenNonDuplicateID(),
						hghligHt: true,
					},
				};
			});
			let row = addArry[0];
			// let showArry = JSON.parse(JSON.stringify(state.tableData)); // state.responseData.push(row);
			state.addList.unshift(row);
			state.tableData = [...state.responseData, ...state.addList];

			const $table = xTable1.value;
			$table.setActiveRow(row);
			$table.clearCheckboxRow();
			$table.toggleCheckboxRow(state.addList[0]); //默认选中第一行
			state.selecttableData = [state.addList[0]]; //拿到选择数据
			// state.tableData = [...state.responseData, ...state.addList];

			// state.tableData = JSON.parse(JSON.stringify([...state.tableData, ...addArry]));
			// console.log(toRaw(state.tableData), '11111111111');
			ElMessage.success({
				message: '新增1行空白栏',
				type: 'success',
			});
			// 计算滚动高度
			let heightpx = state.responseData.length * 20;
			setTimeout(() => {
				document.getElementsByClassName('vxe-table--body-wrapper')[0].scrollTo(0, heightpx);
			}, 100);
		};

		// 银行数据新增
		const addbankShow = () => {
			let addArry = defaultBlankDataShow.map((item: any) => {
				return {
					...item,
					...{
						webid: GenNonDuplicateID(),
					},
				};
			});
			state.bankFrom.shoWData = JSON.parse(JSON.stringify([...state.bankFrom.shoWData, ...addArry]));
			// console.log(toRaw(state.tableData), '11111111111');
			ElMessage.success({
				message: '新增1行空白栏',
				type: 'success',
			});
		};

		// 弹窗删除
		const deleteTable_show: any = async () => {
			let webAddArry: any = [];
			let reeData: any = [];
			state.bankFrom.selectData.forEach((item: any) => {
				if (item.iswebAdd == true) {
					webAddArry.push(item);
				} else {
					reeData.push(item);
				}
			});
			// 判断前端数据是否有值
			let webDelet = () => {
				if (webAddArry.length != 0) {
					// 前端删除
					state.bankFrom.shoWData = state.bankFrom.shoWData.filter((item: any) => {
						return !webAddArry.find((_item: any) => _item.webid === item.webid);
					});
				}
			};

			let resDelet = async () => {
				if (reeData.length != 0) {
					let { code }: object = await axios_waydel(
						reeData.map((item: any) => {
							return item.id;
						})
					);
					// console.log(code, '11111111');
					if (code == 200) {
						getplaData();
					}
				}
			};
			await resDelet();
			await webDelet();
		};

		/**
		 * @Author: lilin_:）
		 * @name: 删除数据
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const deleteTable: any = async () => {
			let webAddArry: any = [];
			let reeData: any = [];
			state.selecttableData.forEach((item: any) => {
				if (item.iswebAdd == true) {
					webAddArry.push(item);
				} else {
					reeData.push(item);
				}
			});
			// 判断前端数据是否有值
			let webDelet = () => {
				if (webAddArry.length != 0) {
					// 前端删除
					state.addList = state.addList.filter((item: any) => {
						return !webAddArry.find((_item: any) => _item.webid === item.webid);
					});
					state.selecttableData = [];
					state.tableData = [...state.responseData, ...state.addList];
				}
			};

			let resDelet = async () => {
				if (reeData.length != 0) {
					let { code }: object = await axios_ticketdel(
						reeData.map((item: any) => {
							return item.id;
						})
					);

					// console.log(code, '11111111');
					if (code == 200) {
						state.selectFrom.on = 1; //状态
						gitTableList();
					}
				}
			};
			await resDelet();
			await webDelet();
		};

		/**
		 * @Author: lilin_:）
		 * @name: 高级导出功能
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const funnelEvent = () => {
			const $table = xTable1.value;
			$table.openExport();
		};

		/**
		 * @Author: lilin_:）
		 * @name: 打印表格
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const printTab = () => {
			const $table = xTable1.value;
			$table.print({
				sheetName: '打印发票台账',
				style: printStyle, //自定义样式
				columns: [
					{ field: 'num' },
					{ field: 'amount' },
					{ field: 'ticketIssuanceTime' },
					{ field: 'dueTime' },
					{ field: 'ticketIssuingUnitId' },
					{ field: 'acceptanceUnitId' },
					{ field: 'paymentTime' },
					{ field: 'receivingUnitId' },
					{ field: 'wayOfPayingId' },
					{ field: 'intermediaryUnitId' },
					{ field: 'startTime' },
					{ field: 'redemptionTime' },
					{ field: 'interest' },
					{ field: 'discountRate' },
					{ field: 'invoiceBack' },
					// { field: 'pictureUrl' },
					{ field: 'remarks' },
					{ field: 'contractId' },
				],
				beforePrintMethod: ({ content }) => {
					// 拦截打印之前，返回自定义的 html 内容
					// return topHtml + content + bottomHtml;
					return content;
				},
			});
		};

		// 展示内容下拉搜索
		const getSelectLabel = (value, list) => {
			let item = list.find((item) => item.id == value);
			return item ? item.unitName : null;
		};
		//付款方式
		const getSelectLabel_play = (value, list) => {
			let item = list.find((item) => item.id == value);
			return item ? item.type : null;
		};

		// 新增付出方式
		const add_shouw = () => {
			getplaData();
			state.bankFrom.isshow = true;
		};

		//实时更新弹窗
		const editClosedEvent_show: VxeTableEvents.EditClosed = ({ row, column }) => {
			// let getRow: any = row;
			if (row.iswebAdd) {
				// 走保存接口
				axios_wayadd(row).then((res) => {
					// console.log(res, '是否啊添加');
					if (res.code == 200) {
						getplaData();
					}
				});
			} else {
				axios_wayup(row).then((res) => {
					if (res.code == 200) {
						getplaData();
					}
				});
			}
		};

		// 上传文件
		let uploadingbutton = async () => {
			// console.log(toRaw(item), 'item');
			let item = state.showFileList.sasveFileItem;

			try {
				const { files } = await VXETable.readFile({
					multiple: true,
				});
				// 数据表 1出纳表 2合同表 3商票台账
				let params = {
					dataSheet: 3,
					id: item.id,
				};
				let formData = new FormData();
				files.forEach((item) => {
					formData.append('files', item);
				});
				axios_fileupload(formData, params).then((res: any) => {
					if (res.code == 200) {
						state.selectFrom.on = 0; //状态
						shuaxingFileListFun();
						VXETable.modal.alert(`共：${files.length} 个文件`);
					}
				});

				// 开始处理数据
			} catch (e) {
				ElMessage.error({
					message: '上传出错啦',
					type: 'error',
				});
			}
		};

		let download = (item: any) => {
			// console.log(toRaw(item), '11111111111111111111');

			if (!item.name) {
				ElMessage.error({
					message: '当前没有下载资源',
					type: 'error',
				});
				return;
			}

			// let pictureUrlArry = item.pictureUrl.split(',');
			// if (pictureUrlArry.length == 0) {
			// 	ElMessage.error({
			// 		message: '当前没有下载资源',
			// 		type: 'error',
			// 	});
			// 	return;
			// }

			let downloadFun = () => {
				// const suffix = item.substring(item.lastIndexOf('.'), item.length);
				let url = `${import.meta.env.VITE_API_URL}/file/download/${item.name}`;
				const x = new XMLHttpRequest();
				x.open('GET', url, true);
				x.responseType = 'blob';
				x.onload = function () {
					const url = window.URL.createObjectURL(x.response);
					const a = document.createElement('a');
					a.href = url;
					a.setAttribute('download', item.name);
					a.click();
				};
				x.send();
			};

			downloadFun();
		};

		// 删除文件
		let deleteFile = (item: any) => {
			console.log(item, '1111');
			// 提示
			ElMessageBox.confirm(`是否删除当前文件名称${item.name}`, '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(() => {
					let resData = {
						name: item.name,
						id: state.showFileList.sasveFileItem.id,
						dataSheet: 3,
					};
					axiosGetFiledel(resData).then((res: any) => {
						// console.log(res, 'async');
						ElMessage({
							type: 'success',
							message: '删除成功',
						});
						shuaxingFileListFun();
					});
				})
				.catch(() => {
					ElMessage({
						type: 'info',
						message: '取消删除',
					});
				});
		};

		const showAmendFun = () => {
			if (state.selecttableData.length == 1) {
				let row = state.selecttableData[0];
				row.hghligHt = true;
				const $table = xTable1.value;
				$table.setActiveRow(row);
			} else if (state.selecttableData.length == 0) {
				VXETable.modal.message({ content: '您还没有选中行', status: 'warning' });
			} else {
				VXETable.modal.message({ content: '只能选中一行编辑', status: 'warning' });
			}
		};

		// 改变颜色样式
		const rowClassName: VxeTablePropTypes.RowClassName = ({ row }) => {
			// console.log(row, 'rowIndex');
			if (row.hghligHt) {
				return 'row-green';
			}
			return null;
		};

		// 回显合同单位ID
		const getSelectLabelelListTop = (value, list) => {
			let item = list.find((item) => item.id == value);
			return item ? item.contractName : null;
		};

		return {
			validRules,
			...toRefs(state),
			showAmendFun,
			editClosedEvent, //实时更新
			footerMethod, //合计
			xToolbar, //关联表格
			xTable1, //表格
			addDefaultBlank, //新增空白行
			deleteTable, //删除数据
			funnelEvent, //导出数据
			printTab, //打印
			getSelectLabel, //展示搜索下拉
			getSelectLabel_play, //付出方式

			//弹窗的内容
			add_shouw, //新增弹窗方式
			deleteTable_show, //删除数据
			addbankShow, //新增空白格
			uploadingbutton, //上传文件
			download, //下载
			deleteFile, //删除
			openFileBtn,

			selectAllChangeEvent1,
			selectChangeEvent1,
			selectAllChangeEvent1_show,
			selectChangeEvent1_show,
			editClosedEvent_show,

			searchEvent,
			resetEvent,
			transitionNumber,
			rowClassName,
			getSelectLabelelListTop,
		};
	},
};
</script>

<style scoped lang="scss">
.mytable-style ::v-deep .vxe-body--row.row-green {
	background-color: #bbb;
	color: #fff;
}
</style>
